// content.js - 内容脚本，用于提取页面表格数据
(function() {
    'use strict';
    
    // 存储表格数据
    let tableData = [];
    
    // 分页处理状态
    let paginationState = {
        isProcessing: false,
        currentPage: 1,
        totalPages: 0,
        collectedData: new Map(),
        progress: 0
    };
    
    // 提取表格数据的主函数
    function extractTablesData() {
        const tables = document.querySelectorAll('table');
        const tablesInfo = [];
        
        tables.forEach((table, index) => {
            const tableInfo = extractSingleTable(table, index);
            if (tableInfo && tableInfo.data.length > 0) {
                tablesInfo.push(tableInfo);
            }
        });
        
        return tablesInfo;
    }
    
    // 提取单个表格的数据
    function extractSingleTable(table, tableIndex) {
        try {
            const rows = table.querySelectorAll('tr');
            if (rows.length === 0) return null;
            
            const data = [];
            let maxCols = 0;
            
            // 遍历所有行
            rows.forEach((row, rowIndex) => {
                const cells = row.querySelectorAll('td, th');
                const rowData = [];
                
                cells.forEach(cell => {
                    // 获取单元格文本内容，处理换行和空白字符
                    let text = cell.innerText || cell.textContent || '';
                    text = text.trim().replace(/\s+/g, ' ');
                    
                    // 处理合并单元格
                    const colspan = parseInt(cell.getAttribute('colspan')) || 1;
                    const rowspan = parseInt(cell.getAttribute('rowspan')) || 1;
                    
                    // 添加单元格数据
                    for (let i = 0; i < colspan; i++) {
                        rowData.push(text);
                    }
                });
                
                if (rowData.length > 0) {
                    data.push(rowData);
                    maxCols = Math.max(maxCols, rowData.length);
                }
            });
            
            // 标准化所有行的列数
            data.forEach(row => {
                while (row.length < maxCols) {
                    row.push('');
                }
            });
            
            // 生成表格描述
            const tableDescription = generateTableDescription(table, tableIndex, data);
            
            return {
                index: tableIndex,
                description: tableDescription,
                data: data,
                rowCount: data.length,
                colCount: maxCols,
                element: table // 保存表格元素引用
            };
            
        } catch (error) {
            console.error('提取表格数据时出错:', error);
            return null;
        }
    }
    
    // 生成表格描述
    function generateTableDescription(table, index, data) {
        // 尝试从表格周围找到描述性文本
        let description = `表格 ${index + 1}`;
        
        // 查找表格标题
        const caption = table.querySelector('caption');
        if (caption && caption.textContent.trim()) {
            description = `表格 ${index + 1}: ${caption.textContent.trim()}`;
        } else {
            // 查找前面的标题元素
            let prev = table.previousElementSibling;
            while (prev && prev.tagName) {
                if (['H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(prev.tagName)) {
                    const titleText = prev.textContent.trim();
                    if (titleText) {
                        description = `表格 ${index + 1}: ${titleText}`;
                        break;
                    }
                }
                prev = prev.previousElementSibling;
            }
        }
        
        // 添加表格尺寸信息
        if (data.length > 0) {
            description += ` (${data.length}行 × ${data[0].length}列)`;
        }
        
        return description;
    }
    
    // 检测表格是否有分页功能
    function detectPagination(table) {
        const paginationSelectors = [
            // 常见的分页选择器
            '.pagination', '.pager', '.page-nav', '.page-numbers',
            '[class*="page"]', '[class*="pag"]',
            '.next', '.prev', '.more', '.load-more',
            '[onclick*="page"]', '[onclick*="next"]', '[onclick*="prev"]',
            'button[class*="page"]', 'a[class*="page"]',
            '.ant-pagination', '.el-pagination', '.layui-laypage',
            '.bootstrap-pagination', '.mui-pagination'
        ];
        
        // 搜索表格附近的分页控件
        let searchContainer = table.parentElement;
        let searchDepth = 0;
        const maxSearchDepth = 5;
        
        while (searchContainer && searchDepth < maxSearchDepth) {
            for (const selector of paginationSelectors) {
                const paginationElement = searchContainer.querySelector(selector);
                if (paginationElement) {
                    return {
                        hasPagination: true,
                        paginationElement: paginationElement,
                        type: getPaginationType(paginationElement)
                    };
                }
            }
            
            // 检查是否包含分页相关的按钮或元素
            const buttons = searchContainer.querySelectorAll('button');
            for (const button of buttons) {
                const buttonText = button.textContent.toLowerCase();
                if (buttonText.includes('下一页') || buttonText.includes('上一页') || 
                    buttonText.includes('next') || buttonText.includes('prev') ||
                    buttonText.includes('更多') || buttonText.includes('加载') ||
                    /第\s*\d+.*页/.test(buttonText)) {
                    return {
                        hasPagination: true,
                        paginationElement: searchContainer,
                        type: getPaginationType(button)
                    };
                }
            }
            
            searchContainer = searchContainer.parentElement;
            searchDepth++;
        }
        
        // 检查全局分页控件
        for (const selector of paginationSelectors) {
            const paginationElement = document.querySelector(selector);
            if (paginationElement) {
                return {
                    hasPagination: true,
                    paginationElement: paginationElement,
                    type: getPaginationType(paginationElement)
                };
            }
        }
        
        return { hasPagination: false };
    }
    
    // 获取分页类型
    function getPaginationType(paginationElement) {
        const text = paginationElement.textContent.toLowerCase();
        const className = paginationElement.className.toLowerCase();
        
        if (text.includes('下一页') || text.includes('next') || className.includes('next')) {
            return 'next';
        }
        if (text.includes('更多') || text.includes('more') || text.includes('加载') || className.includes('more')) {
            return 'loadMore';
        }
        if (/\d/.test(text) || className.includes('page')) {
            return 'numbered';
        }
        return 'unknown';
    }
    
    // 处理分页表格数据收集
    async function handlePaginatedTableData(request, sendResponse) {
        try {
            if (paginationState.isProcessing) {
                sendResponse({
                    success: false,
                    error: '分页数据收集正在进行中，请稍候...'
                });
                return;
            }
            
            paginationState.isProcessing = true;
            paginationState.currentPage = 1;
            paginationState.progress = 0;
            
            const tableIndex = parseInt(request.tableIndex);
            const tables = extractTablesData();
            
            if (tableIndex >= 0 && tableIndex < tables.length) {
                const table = tables[tableIndex];
                const paginationInfo = detectPagination(table.element);
                
                if (paginationInfo.hasPagination) {
                    const allData = await collectPaginatedData(table, paginationInfo);
                    
                    sendResponse({
                        success: true,
                        tables: [{
                            ...table,
                            data: allData,
                            rowCount: allData.length,
                            description: table.description + ' (完整分页数据)'
                        }]
                    });
                } else {
                    sendResponse({
                        success: true,
                        tables: [table]
                    });
                }
            } else {
                sendResponse({
                    success: false,
                    error: '无效的表格索引'
                });
            }
            
        } catch (error) {
            sendResponse({
                success: false,
                error: '收集分页数据失败: ' + error.message
            });
        } finally {
            paginationState.isProcessing = false;
        }
    }
    
    // 收集分页数据
    async function collectPaginatedData(table, paginationInfo) {
        const allData = [...table.data]; // 复制当前页数据
        let hasMorePages = true;
        let attempts = 0;
        const maxAttempts = 50; // 最大尝试次数，防止无限循环
        
        while (hasMorePages && attempts < maxAttempts) {
            attempts++;
            paginationState.currentPage = attempts + 1;
            
            // 尝试触发下一页
            const nextPageSuccess = await triggerNextPage(paginationInfo);
            
            if (!nextPageSuccess) {
                break;
            }
            
            // 等待页面加载
            await wait(2000);
            
            // 提取新页面的表格数据
            const newTableData = extractSingleTable(table.element, table.index);
            
            if (newTableData && newTableData.data.length > 0) {
                // 检查是否有新数据（去除表头）
                const newRows = newTableData.data.slice(1); // 假设第一行是表头
                const existingDataString = allData.slice(1).map(row => row.join('|')).join('\n');
                const newDataString = newRows.map(row => row.join('|')).join('\n');
                
                if (newDataString && !existingDataString.includes(newDataString)) {
                    allData.push(...newRows);
                    paginationState.progress = Math.round((attempts / maxAttempts) * 100);
                } else {
                    // 没有新数据，可能已到最后一页
                    break;
                }
            } else {
                break;
            }
            
            // 检查是否还有下一页
            hasMorePages = checkHasMorePages(paginationInfo);
        }
        
        paginationState.totalPages = attempts;
        paginationState.progress = 100;
        
        return allData;
    }
    
    // 触发下一页
    async function triggerNextPage(paginationInfo) {
        try {
            const { paginationElement, type } = paginationInfo;
            
            switch (type) {
                case 'next':
                    // 找“下一页”按钮
                    let nextButton = paginationElement.querySelector('button:not(:disabled)');
                    const buttons = paginationElement.querySelectorAll('button');
                    
                    for (const button of buttons) {
                        const text = button.textContent.toLowerCase();
                        if ((text.includes('下一页') || text.includes('next')) && 
                            !button.disabled && !button.classList.contains('disabled')) {
                            nextButton = button;
                            break;
                        }
                    }
                    
                    if (nextButton) {
                        nextButton.click();
                        return true;
                    }
                    break;
                    
                case 'loadMore':
                    // 找“加载更多”按钮
                    let loadMoreButton = paginationElement;
                    const loadButtons = paginationElement.querySelectorAll('button');
                    
                    for (const button of loadButtons) {
                        const text = button.textContent.toLowerCase();
                        if ((text.includes('更多') || text.includes('加载') || text.includes('more')) && 
                            !button.disabled) {
                            loadMoreButton = button;
                            break;
                        }
                    }
                    
                    if (loadMoreButton && !loadMoreButton.disabled) {
                        loadMoreButton.click();
                        return true;
                    }
                    break;
                    
                case 'numbered':
                    // 找下一个页码
                    const currentPageNum = paginationState.currentPage;
                    const allButtons = paginationElement.querySelectorAll('button');
                    
                    for (const button of allButtons) {
                        const text = button.textContent.trim();
                        if (text === String(currentPageNum + 1) && !button.disabled) {
                            button.click();
                            return true;
                        }
                    }
                    
                    // 如果没有找到具体页码，尝试找“下一页”按钮
                    for (const button of allButtons) {
                        const text = button.textContent.toLowerCase();
                        if ((text.includes('下一页') || text.includes('next')) && 
                            !button.disabled) {
                            button.click();
                            return true;
                        }
                    }
                    break;
                    
                default:
                    // 通用处理：尝试找任何可用的分页按钮
                    const allBtns = paginationElement.querySelectorAll('button:not(:disabled)');
                    for (const btn of allBtns) {
                        const btnText = btn.textContent.toLowerCase();
                        if (btnText.includes('下一页') || btnText.includes('next') ||
                            btnText.includes('更多') || btnText.includes('加载')) {
                            btn.click();
                            return true;
                        }
                    }
                    break;
            }
            
            return false;
        } catch (error) {
            console.error('触发下一页失败:', error);
            return false;
        }
    }
    
    // 检查是否还有更多页
    function checkHasMorePages(paginationInfo) {
        try {
            const { paginationElement, type } = paginationInfo;
            
            switch (type) {
                case 'next':
                    const buttons = paginationElement.querySelectorAll('button');
                    for (const button of buttons) {
                        const text = button.textContent.toLowerCase();
                        if ((text.includes('下一页') || text.includes('next')) && 
                            !button.disabled && !button.classList.contains('disabled')) {
                            return true;
                        }
                    }
                    return false;
                    
                case 'loadMore':
                    const loadButtons = paginationElement.querySelectorAll('button');
                    for (const button of loadButtons) {
                        const text = button.textContent.toLowerCase();
                        if ((text.includes('更多') || text.includes('加载') || text.includes('more')) && 
                            !button.disabled && button.style.display !== 'none') {
                            return true;
                        }
                    }
                    return false;
                    
                case 'numbered':
                    const currentPageNum = paginationState.currentPage;
                    const allButtons = paginationElement.querySelectorAll('button');
                    
                    // 检查是否有更大的页码
                    for (const button of allButtons) {
                        const text = button.textContent.trim();
                        const pageNum = parseInt(text);
                        if (!isNaN(pageNum) && pageNum > currentPageNum && !button.disabled) {
                            return true;
                        }
                    }
                    
                    // 检查是否有“下一页”按钮
                    for (const button of allButtons) {
                        const text = button.textContent.toLowerCase();
                        if ((text.includes('下一页') || text.includes('next')) && 
                            !button.disabled) {
                            return true;
                        }
                    }
                    return false;
                    
                default:
                    // 通用检查
                    const allBtns = paginationElement.querySelectorAll('button:not(:disabled)');
                    for (const btn of allBtns) {
                        const btnText = btn.textContent.toLowerCase();
                        if (btnText.includes('下一页') || btnText.includes('next') ||
                            btnText.includes('更多') || btnText.includes('加载')) {
                            return true;
                        }
                    }
                    return false;
            }
        } catch (error) {
            console.error('检查是否有更多页失败:', error);
            return false;
        }
    }
    
    // 等待函数
    function wait(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    
    // 监听来自popup的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
        if (request.action === 'getTables') {
            try {
                const tables = extractTablesData();
                // 检测每个表格是否有分页
                const tablesWithPagination = tables.map(table => ({
                    ...table,
                    hasPagination: detectPagination(table.element)
                }));
                
                sendResponse({
                    success: true,
                    tables: tablesWithPagination,
                    count: tablesWithPagination.length
                });
            } catch (error) {
                sendResponse({
                    success: false,
                    error: error.message
                });
            }
        } else if (request.action === 'getTableData') {
            try {
                const tables = extractTablesData();
                let selectedTables = [];
                
                if (request.tableIndex === 'all') {
                    selectedTables = tables;
                } else {
                    const index = parseInt(request.tableIndex);
                    if (index >= 0 && index < tables.length) {
                        selectedTables = [tables[index]];
                    }
                }
                
                sendResponse({
                    success: true,
                    tables: selectedTables
                });
            } catch (error) {
                sendResponse({
                    success: false,
                    error: error.message
                });
            }
        } else if (request.action === 'getTableDataWithPagination') {
            // 处理分页表格数据收集
            handlePaginatedTableData(request, sendResponse);
            return true; // 保持异步响应
        } else if (request.action === 'getPaginationProgress') {
            sendResponse({
                success: true,
                progress: paginationState.progress,
                currentPage: paginationState.currentPage,
                totalPages: paginationState.totalPages,
                isProcessing: paginationState.isProcessing
            });
        }
        
        return true; // 保持消息通道开放以进行异步响应
    });
    
    // 页面加载完成后立即提取表格（用于缓存）
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            tableData = extractTablesData();
        });
    } else {
        tableData = extractTablesData();
    }
    
})();